package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.thread.UserThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version: 1.0
 * @Author: ljy
 * @description: 拦截器，拦截小程序端的请求
 * @date: 2025-07-31 17:10
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 不是controller方法，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //2. 读取请求头中的token
        String authorization = request.getHeader("authorization");
        //3. 如果为空，则返回401
        if (StringUtils.isEmpty(authorization)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //4.解析token
        Claims claims = tokenService.parseToken(authorization);

        if (ObjectUtil.isEmpty(claims)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //5. 获取用户信息
        Long userId = MapUtil.get(claims, "userId", Long.class);
        //6. 将用户信息保存到ThreadLocal
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
